import os
import sys
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_dir)
print(base_dir)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "webservices.settings")
import json
from datetime import datetime
from common.account.models import LokiInformation

with open("/home/ubuntu/tmp.json", encoding="utf-8") as file:
    lines = [l.strip() for l in file]
    bulk = []
    user_id_list = []
    bulk_size = 1000
    counter = 0
    round = 0
    for l in lines:
        account_dct = json.loads(l)
        if not account_dct['user_id']:
            continue
        device = LokiInformation(
            user_id=account_dct['user_id'],
            aid=account_dct['aid'],
            channel=account_dct['chn'] if account_dct['chn'] else 'default_chn',
            ip=account_dct['ip'] if account_dct['ip'] else '1.1.1.1',
            registered_at=datetime.strptime(account_dct['registered'], '%Y-%m-%d %H:%M:%S'),
            active_at=datetime.strptime(account_dct['active_at'], '%Y-%m-%d %H:%M:%S'),
        )
        bulk.append(device)
        if len(bulk) > bulk_size:
            round += 1
            LokiInformation.objects.bulk_create(bulk)
            print("successful count: %s round: %s" % (counter, round))
            bulk = []
        counter += 1
    LokiInformation.objects.bulk_create(bulk)
    # print(device_dct, counter)
